﻿using AngleExpress.service;
using AngleExpress.utils;
using System;
using System.IO;
using System.Windows;
using System.Windows.Shapes;

namespace AngleExpress
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void btn_Login_Click(object sender, RoutedEventArgs e)
        {
            Loading.Visibility = Visibility.Visible;
            var userName = this.TbUserName.Text.Trim();
            var password = this.PbPassword.Password.Trim();
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                Utils.ShowWarn("请输入用户名和密码");
                Loading.Visibility = Visibility.Hidden;
                return;
            }

            Service service = Service.Instance();
            LoginResult loginInfo = await service.Login(userName, password);
            if (loginInfo.errMsg != null)
            {
                Utils.ShowWarn(loginInfo.errMsg);
                Loading.Visibility = Visibility.Hidden;
                return;
            }

            SystemInfoResult systemInfo =  await service.GetSystemConfig(loginInfo.data.userInfo.id);
            if (systemInfo.errMsg != null)
            {
                Utils.ShowWarn(systemInfo.errMsg);
                Loading.Visibility = Visibility.Hidden;
                return;
            }

            if (systemInfo.data == "[]")
            {
                Utils.ShowWarn("此用户没有分配任何客户!");
                Loading.Visibility = Visibility.Hidden;
                return;
            }

            if (!File.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AutoUpdate.exe")))
            {
                Utils.ShowError("找不到关联程序组件，启动失败");
                Loading.Visibility = Visibility.Hidden;
                return;
            }

            Content contentWindow = new Content(loginInfo.data.userInfo.id, loginInfo.data.userInfo.name,loginInfo.data.userInfo.day,systemInfo.data);
            contentWindow.Show();
            this.Close();
        }

        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

    }
}
